package com.huilian.iotbox.admin.wap.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huilian.iotbox.admin.wap.dao.MemberDao;
import com.huilian.iotbox.admin.wap.service.*;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.dto.MemberDto;
import com.huilian.iotbox.data.dto.MemberStats;
import com.huilian.iotbox.data.dto.MemberStoreBalanceDto;
import com.huilian.iotbox.data.enums.*;
import com.huilian.iotbox.data.po.Label;
import com.huilian.iotbox.data.service.LogManipulateService;
import com.huilian.iotbox.data.utils.DateTimeUtils;
import com.huilian.iotbox.data.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class MemberServiceImpl implements MemberService {

    @Resource
    private MemberDao memberDao;
    @Autowired
    private OrderService orderService;
    @Autowired
    private RabbitSenderService rabbitSenderService;
    @Resource
    private LogManipulateService logManipulateService;

    @Resource
    private MemberStoreBalanceService memberStoreBalanceService;

    /**
     * 公众号-兑换商城推送礼品的通知记录
     *
     * @param memberDto
     * @return
     */
    @Override
    public ServerResponse findList(MemberDto memberDto) {
        PageHelper.startPage(memberDto.getPageNum(), memberDto.getPageSize(), true);
        memberDto.setUserId(memberDto.getUserInfo().getId());
        List<MemberVo> memberStoreBalanceList = memberDao.findMemberList(memberDto);
        PageInfo pageResult = new PageInfo(memberStoreBalanceList);
        return ServerResponse.createBySuccess(pageResult);
    }


    @Override
    public ServerResponse getMemberStatsData(MemberDto memberDto) {
        memberDto.setYesterday(DateTimeUtils.getYesterday());
        MemberStats memberStats = memberDao.getMemberStatsData(memberDto);
        return ServerResponse.createBySuccess(memberStats);
    }


    @Override
    public PageInfo<MemberStats> findStatsGroupByStore(MemberDto memberDto) {
        PageHelper.startPage(memberDto.getPageNum(), memberDto.getPageSize(), true);
        memberDto.setYesterday(DateTimeUtils.getYesterday());
        List<MemberStats> memberStoreBalanceList = memberDao.findStatsGroupByStore(memberDto);
        return new PageInfo<>(memberStoreBalanceList);
    }


    @Override
    public PageInfo<MemberVo> findByStoreId(MemberDto memberDto) {
        String sort = memberDto.getOrderBy() + " " + memberDto.getSort();
        PageHelper.startPage(memberDto.getPageNum(), memberDto.getPageSize(), sort);
        memberDto.setYesterday(DateTimeUtils.getYesterday());
        List<MemberVo> memberStoreBalanceList = memberDao.findByStoreId(memberDto);
        return new PageInfo<>(memberStoreBalanceList);
    }

    @Override
    public MemberVo findByMemberIdMerchantStoreId(MemberDto memberDto) {

        if (StringUtils.isEmpty(memberDto.getId())) {
            throw new RuntimeException("会员ID不能为空");
        }

        if (StringUtils.isEmpty(memberDto.getMerchantStoreId())) {
            throw new RuntimeException("场地ID不能为空");
        }

        MemberVo memberVo = memberDao.findByMemberIdMerchantStoreId(memberDto);

        OrderVo orderVo = orderService.statisticsOneMemberAllTurnoverByMemberId(memberDto.getUserInfo(), memberDto.getId(), memberDto.getMerchantStoreId());

        log.info("orderVo.getTurnover():{}", orderVo.getTurnover());
        memberVo.setTotalPay(orderVo.getTurnover());

        return memberVo;
    }

    @Override
    public ServerResponse findMultiConditionPayCoins(MemberDto memberDto, HttpServletRequest request) {
        //计算总共要派出的币 是否超出余币
//        if ((memberDto.getTotal() * memberDto.getSendCoin()) > memberDto.getUserInfo().getWelfareReturnCoinSum()) {
//                return ServerResponse.createByError("送出的游戏币不能超过" + memberDto.getUserInfo().getWelfareReturnCoinSum() + "个");
//        }
        //发mq处理派发币
        rabbitSenderService.sendReplayMemberDistributionCurrency(memberDto);
        String remark = "多会员派发币:总派发" + memberDto.getTotal() + "人;每人" + memberDto.getSendCoin() + "币;共计派发" + memberDto.getTotal() * memberDto.getSendCoin() + "币";
        logManipulateService.insert(memberDto.getUserInfo(), memberDto.toString(), remark, request, ServerResponse.createBySuccess(), null, LogManipulateTypeEnum.SEND_WELFARE.getCode());
        return ServerResponse.createBySuccess();
    }

    @Override
    public MemberDto queryById(Long memberId) {
        return memberDao.queryById(memberId);
    }



    @Override
    public PageInfo<MemberVo> findByMerchantStoreId(MemberDto memberDto) {
        PageHelper.startPage(memberDto.getPageNum(), memberDto.getPageSize(), true);
        List<MemberVo> memberVoList = memberDao.findByMerchantStoreId(memberDto);
        return new PageInfo<>(memberVoList);
    }

    @Override
    public MemberVo findById(MemberDto memberDto) {
        MemberVo memberVo = memberDao.findById(memberDto.getId());
        this.findMemberBalance(memberVo, memberDto);
        if (StringUtils.isEmpty(memberVo.getNickName())) {
            if (org.apache.commons.lang3.StringUtils.isEmpty(memberVo.getOpenId())) {
                memberVo.setNickName("支付宝用户");
            } else {
                memberVo.setNickName("微信用户");
            }
        }
        return memberVo;
    }
    private void findMemberBalance(MemberVo memberVo, MemberDto memberDto) {
        if (!ObjectUtils.isEmpty(memberVo)) {
            if (!ObjectUtils.isEmpty(memberDto.getMerchantStoreId())) {
                MemberStoreBalanceDto memberStoreBalanceDto = new MemberStoreBalanceDto();
                memberStoreBalanceDto.setMemberId(memberVo.getId());
                memberStoreBalanceDto.setMerchantStoreId(memberDto.getMerchantStoreId());
                MemberStoreBalanceVo memberStoreBalanceVo = memberStoreBalanceService.findByMemberIdAndMerchantStoreId(memberStoreBalanceDto);
                if (ObjectUtils.isEmpty(memberStoreBalanceVo)) {
                    memberVo.setMemberStoreBalanceId(0L);
                    memberVo.setCurrencyBalance(0);
                    memberVo.setRechargeBalance(0);
                    memberVo.setDonateBalance(0);
                    memberVo.setIntegral(0);
                    memberVo.setLottery(0);
                    memberVo.setMoneyRechargeBalance(BigDecimal.ZERO);
                    memberVo.setMoneyDonateBalance(BigDecimal.ZERO);
                } else {
                    memberVo.setMemberStoreBalanceId(memberStoreBalanceVo.getId());
                    memberVo.setCurrencyBalance(memberStoreBalanceVo.getCurrencyBalance());
                    memberVo.setRechargeBalance(memberStoreBalanceVo.getRechargeBalance());
                    memberVo.setDonateBalance(memberStoreBalanceVo.getDonateBalance());
                    memberVo.setIntegral(memberStoreBalanceVo.getIntegral());
                    memberVo.setLottery(memberStoreBalanceVo.getLottery());
                    memberVo.setMoneyRechargeBalance(memberStoreBalanceVo.getMoneyRechargeBalance());
                    memberVo.setMoneyDonateBalance(memberStoreBalanceVo.getMoneyDonateBalance());
                }
            } else {
                memberVo.setCurrencyBalance(0);
                memberVo.setRechargeBalance(0);
                memberVo.setDonateBalance(0);
                memberVo.setIntegral(0);
                memberVo.setLottery(0);
                memberVo.setMoneyRechargeBalance(BigDecimal.ZERO);
                memberVo.setMoneyDonateBalance(BigDecimal.ZERO);
            }
        }
    }
    /**
     * 判断排序规则
     */
    private String spliceCollation(MemberDto memberDto) {
        // 获取排序关键字和排序方式
        Integer sortKey = memberDto.getSortKey();
        Integer sortBy = memberDto.getSortBy();

        // 定义 SQL 语句
        String sql;
        if (Objects.equals(sortKey, MemberSortEnum.CUMULATIVE_CONSUMPTION.getCode())) {
            sql = "totalPay";
        } else if (Objects.equals(sortKey, MemberSortEnum.SORT_BY_BALANCE.getCode())) {
            sql = "balance";
        } else if (Objects.equals(sortKey, MemberSortEnum.COIN_SORT.getCode())) {
            sql = "coinTotal";
        } else if (Objects.equals(sortKey, MemberSortEnum.SPENDING_TIME.getCode())) {
            sql = "msb.latelyPay";
        } else if (Objects.equals(sortKey, MemberSortEnum.CAST_CURRENCY_SORT.getCode())) {
            sql = "cumulativeCoin";
        } else {
            sql = null;
        }

        // 根据排序方式设置排序规则
        if (Objects.equals(sortBy, MemberSortEnum.ASCENDING_ORDER.getCode())) {
            sql += " DESC";
        } else if (Objects.equals(sortBy, MemberSortEnum.DESCENDING_ORDER.getCode())) {
            sql += " ASC";
        } else {
            sql = null;
        }
        return sql;
    }

    /**
     * 拼接标签赋值给MemberVo LabelList集合
     *
     * @param memberList
     * @return
     */
    private List<MemberVo> concatenatedTagList(List<MemberVo> memberList) {
        for (MemberVo member : memberList) {
            // 将字符串类型的标签 ID 列表和标签名称列表转换为 List<Label> 类型
            List<String> labelIds = new ArrayList<>();
            List<String> labelNames = new ArrayList<>();
            if (member.getLabelIds() != null && member.getLabelNames() != null) {
                labelIds = Arrays.asList(member.getLabelIds().split(","));
                labelNames = Arrays.asList(member.getLabelNames().split(","));
            }
            List<Label> labelList = new ArrayList<>();
            for (int i = 0; i < labelIds.size(); i++) {
                Label label = new Label();
                label.setId(Integer.parseInt(labelIds.get(i)));
                label.setName(labelNames.get(i));
                labelList.add(label);
            }
            // 设置 labelList 属性
            member.setLabelList(labelList);
        }
        return memberList;
    }
}
